//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.basic.action;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.ManagerModifyPwdBean;
import net.mingsoft.basic.biz.IManagerBiz;
import net.mingsoft.basic.biz.IModelBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.entity.ModelEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.config.MSProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

@Api(
        tags = {"后端-基础接口"}
)
@Controller
@RequestMapping({"/${ms.manager.path}"})
public class MainAction extends BaseAction {
    @Autowired
    private IModelBiz modelBiz;
    @Autowired
    private IManagerBiz managerBiz;
    @Autowired
    private DataSource dataSource;

    public MainAction() {
    }

    @ApiOperation("加载后台主界面，并查询数据")
    @GetMapping({"/index", "/"})
    public String index(HttpServletRequest request) {
        String managerPath = MSProperties.manager.path;
        ManagerEntity managerSession = BasicUtil.getManager();
        new ArrayList();
        new ModelEntity();
        List<ModelEntity> modelList = this.modelBiz.queryModelByRoleId(managerSession.getRoleId());
        List<BaseEntity> _modelList = new ArrayList();

        for(int i = 0; i < modelList.size(); ++i) {
            ModelEntity _model = (ModelEntity)modelList.get(i);
            if (StringUtils.isBlank(_model.getIsChild())) {
                _modelList.add(_model);
            }
        }

        request.setAttribute("managerSession", managerSession);
        request.setAttribute("modelList", JSONUtil.toJsonStr(modelList));
        request.setAttribute("client", BasicUtil.getDomain() + "/" + managerPath);
        request.setAttribute("app", BasicUtil.getApp());
        return "/index";
    }

    @ApiIgnore
    @GetMapping({"/main"})
    public String main(HttpServletRequest request) {
        return "/main";
    }

    @ApiIgnore
    @ApiOperation("加载UI的表单页面")
    @GetMapping({"/system"})
    public String system(HttpServletRequest request) {
        return "/system";
    }

    @ApiOperation("修改登录密码，若不填写密码则表示不修改")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "oldManagerPassword",
            value = "旧密码",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "newManagerPassword",
            value = "新密码",
            required = true,
            paramType = "query"
    )})
    @LogAnn(
            title = "修改登录密码",
            businessType = BusinessTypeEnum.UPDATE
    )
    @PostMapping({"/updatePassword"})
    @ResponseBody
    public ResultData updatePassword(@ModelAttribute @ApiIgnore ManagerModifyPwdBean managerModifyPwdBean, HttpServletResponse response, HttpServletRequest request) {
        String newManagerPassword = managerModifyPwdBean.getNewManagerPassword();
        ManagerEntity manager = BasicUtil.getManager();
        if (!StringUtils.isBlank(newManagerPassword) && !StringUtils.isBlank(managerModifyPwdBean.getOldManagerPassword())) {
            if (!managerModifyPwdBean.getOldManagerPassword().equals(manager.getManagerPassword())) {
                return ResultData.build().error(this.getResString("manager.password.old.err"));
            } else if (!StringUtil.checkLength(newManagerPassword, 6, 30)) {
                return ResultData.build().error(this.getResString("err.length", new String[]{this.getResString("managerPassword"), "6", "30"}));
            } else {
                manager.setManagerPassword(SecureUtil.md5(newManagerPassword));
                this.managerBiz.updateUserPasswordByUserName(manager);
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
                return ResultData.build().success();
            }
        } else {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("managerPassword")}));
        }
    }

    @ApiOperation("退出系统")
    @GetMapping({"/loginOut"})
    @ResponseBody
    public ResultData loginOut(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultData.build().success();
    }

    @ApiOperation("获取系统配置信息")
    @PostMapping({"/system"})
    @ResponseBody
    public ResultData system(HttpServletResponse response, HttpServletRequest request) {
        Properties props = System.getProperties();
        HashMap<String, Object> map = new HashMap();
        map.put("CPU核数", String.valueOf(Runtime.getRuntime().availableProcessors()));
        map.put("虚拟机内存总量", String.valueOf(Runtime.getRuntime().totalMemory() / 1048576L));
        map.put("虚拟机空闲内存量", String.valueOf(Runtime.getRuntime().freeMemory() / 1048576L));
        map.put("虚拟机使用最大内存量", String.valueOf(Runtime.getRuntime().maxMemory() / 1048576L));
        map.put("系统名称", props.getProperty("os.name"));
        map.put("系统构架", props.getProperty("os.arch"));
        map.put("系统版本", props.getProperty("os.version"));
        map.put("Java版本", props.getProperty("java.version"));
        map.put("Java安装路径", props.getProperty("java.home"));
        CpuInfo cpu = OshiUtil.getCpuInfo();
        map.put("cpu信息", cpu.getCpuModel() + "" + cpu.getCpuNum());
        map.put("内存总量", OshiUtil.getMemory().getTotal() / 1048576L);
        map.put("内存可用", OshiUtil.getMemory().getAvailable() / 1048576L);
        Connection connection = null;

        try {
            connection = this.dataSource.getConnection();
            DatabaseMetaData mtdt = connection.getMetaData();
            map.put("数据库链接", mtdt.getURL());
            map.put("数据库", mtdt.getDatabaseProductName());
            map.put("数据库版本", mtdt.getDatabaseProductVersion());
        } catch (SQLException var8) {
            var8.printStackTrace();
        }

        ServletContext context = request.getServletContext();
        map.put("web容器", context.getServerInfo());
        map.put("发布路径", context.getRealPath(""));
        return ResultData.build().success(map);
    }
}
